<?php
// +----------------------------------------------------------------------
// | MVC路由简单实现
// +----------------------------------------------------------------------
// | Copyright (c) 2019 http://qwn.the2016.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wm
// +----------------------------------------------------------------------

//定义app路径
define('APP_PATH', trim(__DIR__ . '/'));
define('CONTROLLER_SUFFIX', 'Controller');

//获得请求地址
$root    = $_SERVER['SCRIPT_NAME'];
$request = $_SERVER['REQUEST_URI'];

//获得index.php 后面的地址 index.php可以使用伪静态去除
$request = trim(str_replace('/index.php', '', $request), '/');
$params  = [];
//如果为空，则是访问根地址
if (empty($request)) {
    //默认控制器和默认方法
    $controller = 'index';
    $action     = 'index';
} else {
    $params = explode('/', $request);
    //如果function为空 则默认访问index
    if (count($params) < 2) {
        $controller = $params[0];
        $action     = 'index';
        unset($params[0]);
    } else {
        $controller = $params[0];
        $action     = $params[1];
        unset($params[0]);
        unset($params[1]);
    }
}

// 判断文件是否存在
$classname       = ucfirst($controller) . CONTROLLER_SUFFIX;//将控制器首字母大写
$filename        = $classname . '.php';
$controller_path = '/app/controller/';
if (!file_exists(APP_PATH . $controller_path . $filename)) {
    throw new Exception('controller ' . $filename . ' is not exists!');
}

// 把class加载进来
require(APP_PATH . $controller_path . $filename);

// 类是否存在
$classname = str_replace("/", '\\', $controller_path . $classname);
if (!class_exists($classname)) {
    throw new Exception('class ' . $classname . ' is not exists!');
}

// 方法是否存在
$reflectionObj = new ReflectionClass($classname);// 反射类，顾名思义，可以理解为一个类的映射
if (!$reflectionObj->hasMethod($action)) {
    throw new Exception('method ' . $action . ' is not exists!');
}

// 实例化对象
$currentObj = new $classname();

//调用内部function
call_user_func_array([$currentObj, $action], $params);